<template>
  <div class="form-group-content">
    <el-row>
      <el-form
        ref="ruleForm"
        :model="formParams"
        :rules="rules"
        :inline="true"
        :label-position="labelPosition || 'right'"
        :label-width="labelWidth"
        size="small"
      >
        <Items v-for="(item, i) in searchConfig" v-if="!item.slot" ref="name" :key="i" :items="item" :label-position="labelPosition || 'right'" />
        <el-col v-else :span="item.span" class="layout-content">
          <slot :name="item.slot" />
        </el-col>
        <!-- <el-col>
          <el-form-item
            v-if="items.visible === true || items.visible === undefined"
            class="layout-item"
            :class="items.rules && labelPosition !== 'right' ? 'isNeeded' : '' "
            :label="items.label"
            :title="items.label"
            :prop="items.keyIndex"
          >
          </el-form-item>
        </el-col> -->

        <!-- <slot></slot> -->
      </el-form>

      <div v-if="isShowBtns">
        <el-button>取消</el-button>
        <el-button @click="handleConfirm">确定</el-button>
      </div>
    </el-row>
  </div>
</template>
<script>
import Items from './items.vue'
export default {
  name: 'FormGroup',
  components: {
    Items
  },
  props: ['searchConfig', 'labelWidth', 'labelPosition', 'isShowBtns'],
  data() {
    return {
      formParams: {},
      rules: {}
    }
  },
  watch: {
    searchConfig: {
      deep: true,
      handler(newVal) {
        this.formParams = this.getData()
      }
    }
  },
  created() {
    this.initFromParams()
  },
  mounted() {

  },
  methods: {
    resetFields() {
      this.$refs['ruleForm'] && this.$refs['ruleForm'].resetFields()
    },
    initFromParams() {
      this.searchConfig.forEach(v => {
        this.formParams[v.keyIndex] = v.value
        if (v.rules) {
          this.rules[v.keyIndex] = v.rules
        }
      })
    },
    resetFormParams() {
      this.searchConfig.forEach(v => {
        this.formParams[v.keyIndex] = ''
        if (v.rules) {
          this.rules[v.keyIndex] = ''
        }
      })
    },
    async getParams() {
      console.log(111, this.$refs['ruleForm'].validate())
      const result = await this.$refs['ruleForm'].validate()
      if (result) {
        return this.formParams
      } else {
        return null
      }
    },
    getData() {
      const params = {}
      this.searchConfig.forEach(v => {
        params[v.keyIndex] = v.value
      })
      return params
    },
    handleConfirm() {
      console.log(this.formParams, 1999)
      this.$refs['ruleForm'].validate((valid, a, b) => {
        if (valid) {
          alert('submit!')
        } else {
          console.log('error submit!!')
          return false
        }
      })
      return { xxx: 'xxx' }
    }
  }
}
</script>
<style lang="scss">
  .form-group-content {
    .el-form {
      display: flex;
      flex-direction: column;
    }
  }
</style>